package com.iwhalecloud.citybrain.flow.platform.manager.application.listener;

import java.util.Objects;

import com.iwhalecloud.citybrain.flow.platform.manager.application.common.enums.UserEnum;
import com.iwhalecloud.citybrain.flow.platform.manager.application.common.event.CreateParticipantEvent;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.FlowParticipantInfoVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.FlowUser;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowParticipantRepository;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.UserRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @author lilh
 * @date 2019-02-19 22:06
 */
@Component
public class FlowSpringListener {

    @Autowired
    private FlowParticipantRepository flowParticipantRepository;

    @Autowired
    private UserRepository userRepository;

    @Async
    @EventListener
    public void handle(CreateParticipantEvent event) {
        FlowParticipantInfoVo entity = resolveParticipant(event.getCreateParticipantVo());
        flowParticipantRepository.insertParticipant(entity);
        //insertUserIfNecessary(event.getCreateParticipantVo());
    }

    private void insertUserIfNecessary(CreateParticipantEvent.CreateParticipantVo createProcessInstanceDto) {
        if (Objects.nonNull(userRepository.getUserByCode(createProcessInstanceDto.getParticipantId()))) {
            //如果已经存在，则不处理
            return;
        }

        if (StringUtils.isBlank(createProcessInstanceDto.getParticipantId())) {
            return;
        }

        //如果不存在，则备份到user表中
        FlowUser userInfo = new FlowUser();
        userInfo.setUserCode(createProcessInstanceDto.getParticipantId());
        userInfo.setUserId(createProcessInstanceDto.getParticipantId());
        userInfo.setUserName(createProcessInstanceDto.getParticipantName());
        userInfo.setTenantId(0);
        userInfo.setUserType(UserEnum.NORMAL.type());
        userInfo.setCreatorName(createProcessInstanceDto.getFrom());
        userRepository.insertFlowUser(userInfo);

    }

    private FlowParticipantInfoVo resolveParticipant(CreateParticipantEvent.CreateParticipantVo createProcessInstanceDto) {
        FlowParticipantInfoVo entity = new FlowParticipantInfoVo();
        entity.setParticipantId(createProcessInstanceDto.getParticipantId());
        String participantType = "USR";
        if (participantType.equals(createProcessInstanceDto.getParticipantType())) {
            createProcessInstanceDto.setParticipantType("STA");
        }
        entity.setParticipantType("STA");
        entity.setParticipantName(createProcessInstanceDto.getParticipantName());
        return entity;
    }
}
